package com.carbohydrate42.kotlin_compose_demo.compose

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.outlined.ArrowRight
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.carbohydrate42.kotlin_compose_demo.module.EasyBottomSheetDialog
import kotlinx.coroutines.launch

/**
 * 部分组件可以抄出来用 (不过有些已经被收录到 compose 的官方库了)
 * https://github.com/ltttttttttttt/ComposeViews
 *
 * https://github.com/jetpack-compose/jetpack-compose-awesome
 */
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun SomeSheetComponent() {
    BottomDialog()
}


@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun Filters() {
    val filters = listOf(
        "Washer/Dryer", "Ramp access", "Garden", "Cats OK", "Dogs OK", "Smoke-free"
    )
    FlowRow(
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        filters.forEach { title ->
            var selected by remember { mutableStateOf(false) }
            val leadingIcon: @Composable () -> Unit = { Icon(Icons.Default.Check, null) }
            FilterChip(
                selected,
                onClick = { selected = !selected },
                label = { Text(title) },
                leadingIcon = if (selected) leadingIcon else null
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HorizontalPagerWithIndicator() {
    val list = remember {
        mutableStateListOf("香蕉", "苹果", "芒果", "萝卜", "咖啡")
    }

    val state = rememberPagerState(
        initialPage = 0,//初始页码
    )
    val scope = rememberCoroutineScope()

    Column {
        ScrollableTabRow(
            //展示的页码，和Pager的保持一致
            selectedTabIndex = state.currentPage,
        ) {
            list.forEachIndexed { index, data ->
                Box(
                    Modifier
                        .height(40.dp)
                        .width(100.dp)
                        .clickable {
                            scope.launch {
                                // Tab被点击后让Pager中内容动画形式滑动到目标页
                                state.scrollToPage(index, 0f)
                            }
                        }, contentAlignment = Alignment.Center
                ) {
                    Text(text = data)
                }
            }
        }
        HorizontalPager(
            pageCount = list.size,
            state = state,
            modifier = Modifier.fillMaxSize(),
        ) { pagePosition ->
            val color = (0..255)

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color(color.random(), color.random(), color.random())),
                contentAlignment = Alignment.Center
            ) {
                Text(text = list[pagePosition])
            }
        }
    }
}


/**
 * 如下这种不是很好, 还有更高级一种做法, 无需老是套一层 scaffold
 * 参考 https://www.usfl.cn/p/compose-bottom-sheet/
 *
 * 底部弹出式列表
 */

@Composable
fun BottomDialog() {

    var visible by remember {
        mutableStateOf(false)
    }

    Column {
        Button(onClick = {
            visible = true
        }) {
            Text(text = "ShowDialog")
        }
        Text(text = "visible : $visible")
    }


    EasyBottomSheetDialog(
        modifier = Modifier,
        visible = visible,
        cancelable = true,
        canceledOnTouchOutside = true,
        onDismissRequest = {
            visible = false
        }
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(fraction = 0.7f)
                .clip(shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp))
                .background(color = Color(0xFF009688)),
            verticalArrangement = Arrangement.Center
        ) {
            Button(
                modifier = Modifier
                    .align(alignment = Alignment.CenterHorizontally),
                onClick = {
                    visible = false
                }) {
                Text(
                    modifier = Modifier.padding(all = 4.dp),
                    text = "dismissDialog",
                    fontSize = 16.sp
                )
            }
        }
    }
}


/**
 *
 * 全屏的 dialog 显示
 *
 */
@Composable
fun FullScreenDialog() {

    var alertDialog by remember { mutableStateOf(true) }

    if (alertDialog) {
        Dialog(
            onDismissRequest = {
                alertDialog = false
            },
            properties = DialogProperties(
                usePlatformDefaultWidth = false
            ),
        ) {
            Surface(
                modifier = Modifier
                    .fillMaxSize(),
                color = Color.White
            ) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        modifier = Modifier.align(Alignment.TopCenter),
                        text = "top"
                    )
                    Text("center")
                    Text(
                        modifier = Modifier.align(Alignment.BottomCenter),
                        text = "bottom"
                    )
                }
            }
        }
    }


}


@Composable
fun DescriptionList() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp)
    ) {
        Column(modifier = Modifier.padding(10.dp)) {

            repeat(5) { it ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(5.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(text = "Label$it", fontWeight = FontWeight.ExtraBold)
                    Text(text = "Value$it")
                }
            }

        }
    }
}


/**
 * 点击处弹出式单选列表
 */
@Composable
fun SingleSelect() {
    val typeList = mutableListOf(
        "重庆",
        "成都",
        "上海",
        "北京",
        "深圳",
        "香港",
    )
    val isClick = rememberSaveable { mutableStateOf(false) }
    val selectType = rememberSaveable { mutableStateOf("重庆") }
    Column(
        modifier = Modifier.fillMaxWidth(),
    ) {
        Button(
            onClick = { isClick.value = !isClick.value },
            content = {
                Text(text = selectType.value)
            },
        )

        DropdownMenu(
            expanded = isClick.value,
            modifier = Modifier.fillMaxWidth(),
            onDismissRequest = {},
            content = {
                typeList.forEach {
                    DropdownMenuItem(
                        onClick = {
                            isClick.value = !isClick.value
                            selectType.value = it
                        },
                        text = {
                            Text(text = it)
                        },
                    )
                }
            },
        )
    }
}

/**
 * 可展开的列表 (todo 改为树形选择)
 *
 * @param title 列表标题
 * @param modifier Modifier
 * @param endText 列表标题的尾部文字，默认为空
 * @param subItemStartPadding 子项距离 start 的 padding 值
 * @param subItem 子项
 * */
@Composable
fun TreeSelectItem(
    title: String,
    modifier: Modifier = Modifier,
    endText: String = "",
    subItemStartPadding: Int = 8,
    subItem: @Composable () -> Unit
) {
    var isShowSubItem by remember { mutableStateOf(false) }

    val arrowRotateDegrees: Float by animateFloatAsState(if (isShowSubItem) 90f else 0f, label = "")

    Column(modifier = modifier) {
        Row(
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .fillMaxWidth()
                .clickable {
                    isShowSubItem = !isShowSubItem
                }
        ) {
            Text(text = title)
            Row {
                if (endText.isNotBlank()) {
                    Text(
                        text = endText,
                        modifier = modifier
                            .padding(end = 4.dp)
                            .widthIn(0.dp, 100.dp),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                Icon(
                    Icons.Outlined.ArrowRight,
                    contentDescription = title,
                    modifier = Modifier.rotate(arrowRotateDegrees)
                )
            }
        }

        AnimatedVisibility(visible = isShowSubItem) {
            Column(modifier = Modifier.padding(start = subItemStartPadding.dp)) {
                subItem()
            }
        }
    }
}